frappe.provide("frappe.ui");

window.start_scan = function () {
	console.log("start_scan called");
	// 从网页发送消息到 .NET MAUI
	window.location.href = "/_scan_";
}

window.stop_scan = function () {
	console.log("stop_scan stoped");
}

//调用示例    window.on_scan('999')
window.on_scan = function (data) {
	console.log("on_scan called");
	// 创建带有参数的事件
	const scan_event = new CustomEvent('scan_event', { detail: { barcode: data } });
	// 触发事件
	document.dispatchEvent(scan_event);
}

frappe.ui.Scanner = class Scanner {
	constructor(options) {
		this.dialog = null;
		this.handler = null;
		this.options = options;
		this.is_alive = false;

		if (!("multiple" in this.options)) {
			this.options.multiple = false;
		}

		const that = this;

		window.start_scan();

		// 保存 bound 函数的引用
		this.boundDoScan = this.do_scan.bind(this);

		// 使用保存的引用添加监听器
		document.addEventListener('scan_event', this.boundDoScan);
	}

	do_scan(e) {
		console.log(e.detail.barcode);
		var result = { result: { text: e.detail.barcode } };
		if (this.options.on_scan) {
			try {
				this.options.on_scan(result);
			} catch (error) {
				console.error(error);
			}
		}
		if (!this.options.multiple) {
			// 使用保存的引用移除监听器
			document.removeEventListener('scan_event', this.boundDoScan);
			window.stop_scan();
		}
	}
};
